#pragma once

#include "Socket.hpp"
#include "TcpServer.hpp"
#include "Util.hpp"
#include "Log.hpp"
#include <iostream>
#include <string>
#include <memory>
#include <sstream>
#include <functional>
#include <unordered_map>

using namespace SocketModule;
using namespace LogModule;

const std::string gspace = " ";        // 空格
const std::string glinespace = "\r\n"; // 换行符
const std::string glinesep = ": ";

const std::string webroot = "./wwwroot";
const std::string homepage = "index.html";
const std::string page_404 = "/404.html";

class HttpRequest
{
public:
    HttpRequest() : _is_interact(false) {}
    std::string Serialize()
    {
        return std::string();
    }

    void ParseReqLine(std::string &reqline)
    {
        // GET / HTTP/1.1
        std::stringstream ss(reqline);
        ss >> _method >> _uri >> _version;
    }

    bool Deserialize(std::string &reqstr)
    {
        // 提取请求行
        std::string reqline;
        bool res = Util::ReadOneLine(reqstr, &reqline, glinespace);
        if (!res)
        {
            LOG(LogLevel::DEBUG) << "ReadOneLine error";
            return false;
        }
        // 2. 对请求行进行反序列化
        ParseReqLine(reqline);
        LOG(LogLevel::DEBUG) << "_method: " << _method;
        LOG(LogLevel::DEBUG) << "_uri: " << _uri;
        LOG(LogLevel::DEBUG) << "_version: " << _version;
        if (_uri == "/")
            // ./wwwroot/index.html
            _uri = webroot + _uri + homepage;
        else
            // ./wwwroot/a/b/c.html
            _uri = webroot + _uri;
        //  _uri: ./wwwroot/login?username=zhangsan&password=123456

        const std::string temp = "?";
        auto pos = _uri.find(temp);
        if (pos == std::string::npos)
        {
            return true;
        }
        _args = _uri.substr(pos + temp.size());
        _uri = _uri.substr(0, pos);
        _is_interact = true;

        return true;
    }
    std::string Uri() { return _uri; }
    bool isInteract() { return _is_interact; }
    std::string Args() { return _args; }
    ~HttpRequest() {}

private:
    std::string _method;  // 请求方法
    std::string _uri;     // 超链接
    std::string _version; // http协议版本

    std::unordered_map<std::string, std::string> _headers; // key : val
    std::string _blankline;                                // 空行，空行之下：数据正文，空行之上：数据报头
    std::string _text;

    std::string _args;
    bool _is_interact;
};

class HttpResponse
{
public:
    HttpResponse() : _blankline(glinespace), _version("HTTP/1.0")
    {
    }
    std::string Serialize()
    {
        std::string status_line = _version + gspace + std::to_string(_code) + gspace + _desc + glinespace;
        std::string resp_header;
        // std::cout << "##########################" << std::endl;
        // std::cout << status_line;
        // std::cout << "##########################" << std::endl;
        for (auto &header : _headers)
        {
            std::string line = header.first + glinesep + header.second + glinespace;
            resp_header += line;
        }
        return status_line + resp_header + _blankline + _text;
    }
    bool Deserialize(std::string &reqstr)
    {
        return true;
    }
    void SetTargetFile(const std::string &target)
    {
        _targetfile = target;
    }
    void SetCode(int code)
    {
        _code = code;
        switch (_code)
        {
        case 200:
            _desc = "OK";
            break;
        case 404:
            _desc = "Not Found";
            break;
        case 301:
            _desc = "Moved Permanently";
            break;
        case 302:
            _desc = "See Other";
            break;
        default:
            break;
        }
    }

    std::string Uri2Suffix(const std::string &targetfile)
    {
        // ./wwwroot/a/b/c.html
        // https://www.runoob.com/http/http-content-type.html
        auto pos = targetfile.rfind(".");
        if (pos == std::string::npos)
        {
            return "text/html";
        }
        std::string suffix = targetfile.substr(pos);
        if (suffix == ".html" || suffix == ".htm")
            return "text/html";
        else if (suffix == ".jpg")
            return "image/jpeg";
        else if (suffix == "png")
            return "image/png";
        else
            return "";
    }

    void SetHeader(const std::string &key, const std::string &value)
    {
        auto iter = _headers.find(key);
        if (iter != _headers.end())
        {
            return;
        }
        _headers.insert(std::make_pair(key, value));
    }

    bool MakeResponse()
    {
        if (_targetfile == "./wwwroot/favicon.ico")
        {
            LOG(LogLevel::DEBUG) << "用户请求: " << _targetfile << "忽略它";
            return false;
        }
        if (_targetfile == "./wwwroot/redir_test")
        {
            SetCode(301);
            SetHeader("Location", "https://www.qq.com/");
            return true;
        }
        int filesize = 0;
        bool res = Util::ReadFileContent(_targetfile, &_text);
        if (!res)
        {
            _text = "";
            LOG(LogLevel::WARNING) << "client want get : " << _targetfile << " but not found";
            SetCode(404);
            _targetfile = webroot + page_404;
            filesize = Util::FileSize(_targetfile);
            Util::ReadFileContent(_targetfile, &_text);
            std::string suffix = Uri2Suffix(_targetfile);
            SetHeader("Content-Type", suffix);
            SetHeader("Content-Length", std::to_string(filesize));
        }
        else
        {
            LOG(LogLevel::DEBUG) << "读取文件: " << _targetfile;
            SetCode(200);
            filesize = Util::FileSize(_targetfile);
            std::string suffix = Uri2Suffix(_targetfile);
            SetHeader("Conent-Type", suffix);
            SetHeader("Content-Length", std::to_string(filesize));
        }
        return true;
    }
    void SetText(const std::string &t)
    {
        _text = t;
    }
    ~HttpResponse() {}

public:
    std::string _version;
    int _code;
    std::string _desc;

    std::unordered_map<std::string, std::string> _headers;
    std::string _blankline;
    std::string _text;

    std::string _targetfile;
};

using http_func_t = std::function<void(HttpRequest &req, HttpResponse &resp)>;

class Http
{
public:
    Http(uint16_t prot)
        : tsvrp(std::make_unique<TcpServer>(prot))
    {
    }

    void andlerHttpRquest(std::shared_ptr<Socket> &sock, InetAddr &client)
    {
        std::string httpreqstr;
        int n = sock->Recv(&httpreqstr);

        if (n > 0)
        {
            HttpRequest req;
            req.Deserialize(httpreqstr); // 获取第一行
            HttpResponse resp;
            resp.SetTargetFile(req.Uri()); // 根据对方请求链接，建立访问文件路径
                                           // LOG(LogLevel::DEBUG) << resp._targetfile;
            if (req.isInteract())
            {
                // 动态交互
                //  _uri: ./wwwroot/login
                if (_route.find(req.Uri()) == _route.end())
                {
                    // SetCode(302);
                }
                else
                {
                    _route[req.Uri()](req, resp);
                    std::string response_str = resp.Serialize();
                    sock->Send(response_str);
                }
            }
            else
            {
                // 静态资源
                resp.SetTargetFile(req.Uri());
                if (resp.MakeResponse())
                {
                    std::string response_str = resp.Serialize();
                    sock->Send(response_str);
                }
            }

            // if (resp.MakeResponse())
            // {
            //     // 将目标文件的内容，写进_text
            //     std::string response_str = resp.Serialize(); // 序列化
            //     std::cout << response_str;
            //     int n = sock->Send(response_str);
            // }
            // else
            LOG(LogLevel::DEBUG) << "Send error";
            // LOG(LogLevel::DEBUG) << resp._text;
            // HttpResponse resp;
            // //./wwwroot/a/b/c.html
            // resp._version = "HTTP/1.1";
            // resp._code = 200; // success
            // resp._desc = "OK";
            // std::string filename = req.Uri();
            // LOG(LogLevel::DEBUG) << filename;
            // bool res = Util::ReadFileContent(filename, &(resp._text)); // 浏览器请求的资源，一定会存在吗？出错呢？
            // (void)res;
            // std::string response_str = resp.Serialize(); // 序列化
            // int n = sock->Send(response_str);
        }
// #ifndef DEBUG
// #define DEBUG
#ifdef DEBUG
        std::string httpreqstr;
        sock->Recv(&httpreqstr);
        std::cout << httpreqstr; // 是一个长字符串

        HttpResponse resp;
        resp._version = "HTTP/1.1";
        resp._code = 200; // success
        resp._desc = "OK";

        std::string filename = webroot + homepage;
        std::cout << filename;
        bool res = Util::ReadFileContent(filename, &(resp._text)); // 读取html文件
        (void)res;
        std::cout << resp._text;
        std::string response_str = resp.Serialize();
        sock->Send(response_str);
#endif
    }

    void start()
    {
        tsvrp->start([this](std::shared_ptr<Socket> &socket, InetAddr &client)
                     { this->andlerHttpRquest(socket, client); });
    }
    void RegisterService(const std::string name, http_func_t h)
    {
        std::string key = webroot + name; // ./wwwroot/login
        auto iter = _route.find(key);     // 不存在方法
        if (iter == _route.end())
        {
            _route.insert(std::make_pair(key, h));
        }
    }
    ~Http() {}

private:
    std::unique_ptr<TcpServer> tsvrp;
    std::unordered_map<std::string, http_func_t> _route; // 服务及对应的方法
};